package com.wlf.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
* @author 作者 危凌峰
* @version 创建时间：2021年4月28日 上午9:35:15
*/
@RestController
public class SessionController {
	private static Logger logger = LoggerFactory.getLogger(SessionController.class);

	@Value("${server.port}")
	private  String port;

	@RequestMapping("/session")
	public String session(HttpServletRequest request){
		HttpSession session =request.getSession();
		String sessionId = session.getId();
		Map<String,Object> map =new HashMap<>();
		if(StringUtils.isBlank(sessionId)){
			sessionId="未获取到id";
		}
		map.put("userName","赵玉芝");
		map.put("sex","女");
		map.put("remark","嘿嘿嘿!");
		map.put("port",port);
		map.put("ip",this.getIpAddr(request));
		map.put("sessionId",sessionId);
		String returnVal =com.alibaba.fastjson.JSONObject.toJSONString(map);
		logger.info("返回值:{}",returnVal);
		return com.alibaba.fastjson.JSONObject.toJSONString(map);
	}

	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
